package com.sia.springcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sia.springcloud.model.UserInfo;
import com.sia.springcloud.mapper.UserInfoMapper;
import com.sia.springcloud.redis.RedisUtils;
import com.sia.springcloud.result.GridDataResult;
import com.sia.springcloud.result.ResultUtil;
import com.sia.springcloud.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sia.springcloud.utils.JwtUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.print.attribute.standard.JobOriginatingUserName;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.util.*;


/**
 * @Author: Sirius
 * @Date: 2022/1/3 12:07
 * @Description: 用户信息接口实现类
 **/
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 登录验证
     * <p>
     * 将登录用户信息保存到redis中，并将生成的token信息返回
     * 用户权限用auth字段表示，1表示管理员权限，2表示普通用户
     *
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("username", username);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
        if (userInfo == null) {
            return ResultUtil.createSimpleFailureJson("登录失败");
        }


        if (password.equals(userInfo.getPassword())) {
            //设置过时时间为一个月
            String token = JwtUtils.createJWT(UUID.randomUUID().toString(), username, 1000 * 3600 * 24 * 30);
            //获取token放在存入redis之前，保证如果重新登录，原有的token失效
            redisUtils.del(username);
            if (redisUtils.set(username, token)) {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("result","Y");
                userMap.put("message","登录成功");
                userMap.put("username", username);
                userMap.put("token", token);
                userMap.put("auth", userInfo.getPermission());
                userMap.put("role",userInfo.getRole());

                return JSON.toJSONString(userMap);
            }
        }
        return null;
    }


    /**
     * 查询登录用户信息，方便用户进行信息修改
     *
     * @param username
     * @return
     */
    @Override
    public String queryUserInfo(String username) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("username", username);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);

        if(userInfo==null){
            return null;
        }else{
            return JSON.toJSONString(userInfo);
        }
    }


    /**
     * 注销登录
     *
     * @param username
     * @return
     */
    public String logout(String username) {
        if (!StringUtils.isEmpty(username)) {
            if (redisUtils.hasKey(username)) {
                redisUtils.del(username);
                return ResultUtil.createSimpleSuccessJson("退出登录成功");
            }
        }
        return ResultUtil.createSimpleFailureJson("退出登录失败");
    }


    /**
     * 注销账号
     *
     * @param username
     * @return
     */
    public String cancelAccount(String username) {
        if (!StringUtils.isEmpty(username)) {
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("username", username);
            if (userInfoMapper.delete(userInfoQueryWrapper) == 1) {
                return ResultUtil.createSimpleSuccessJson("注销账号成功");
            }
        }
        return ResultUtil.createSimpleFailureJson("注销账号失败");
    }


    /**
     * 添加用户
     *
     * @param userInfo
     * @return
     */
    public String insertUser(UserInfo userInfo) {

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<UserInfo>();
        userInfoQueryWrapper.eq("username", userInfo.getUsername());
        List<UserInfo> userInfoList = userInfoMapper.selectList(userInfoQueryWrapper);
        if (null != userInfoList && userInfoList.size() > 0) {
            return ResultUtil.createSimpleFailureJson("用户新增失败，用户名 " + userInfo.getUsername() + " 已存在");
        }

        userInfoMapper.insert(userInfo);

        return ResultUtil.createSimpleSuccessJson("用户新增成功");
    }


    /**
     * 分页查询用户信息
     *
     * @param start
     * @param limit
     * @return
     */
    public String queryUser(String start, String limit) {

        Integer total = userInfoMapper.selectCount(null);

        Page<UserInfo> userInfoPage = new Page<>();
        userInfoPage.setTotal(total);
        userInfoPage.setCurrent(Integer.parseInt(start));
        userInfoPage.setSize(Integer.parseInt(limit));


        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(userInfoPage, null);
        List<UserInfo> userInfoList = userInfoIPage.getRecords();


        GridDataResult<UserInfo> userInfoListResult = new GridDataResult<>();
        userInfoListResult.setTotal(total);
        userInfoListResult.setRoot(userInfoList);

        return JSON.toJSONString(userInfoListResult);
    }

    /**
     * 批量删除用户
     *
     * @param userIds
     * @return
     */
    public String deleteById(String[] userIds) {

        for (String userId : userIds) {
            int id = Integer.parseInt(userId);
            userInfoMapper.deleteById(id);
        }
        return ResultUtil.createSimpleSuccessJson("用户删除成功");
    }

    /**
     * 更新用户信息
     *
     * @param userInfo
     * @return
     */
    public String updateUser(UserInfo userInfo) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.eq("username", userInfo.getUsername());
        queryWrapper.ne("id", userInfo.getId());
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);

        if (userInfoList != null && userInfoList.size() > 0) {
            return ResultUtil.createSimpleFailureJson("修改失败，用户名 " + userInfo.getUsername() + " 已存在");
        }

        if (userInfoMapper.updateById(userInfo) == 1) {

            return ResultUtil.createSimpleSuccessJson("修改成功");
        }
        return ResultUtil.createSimpleFailureJson("修改失败");
    }


}
